package com.sanpu.kxe.business.main.fragment;

import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseFragment;
import com.sanpu.kxe.business.main.adapter.ProfitsPagerAdapter;
import com.sanpu.kxe.business.main.bean.RebateTotalOutput;
import com.sanpu.kxe.business.main.contract.ProfitsContract;
import com.sanpu.kxe.business.main.presenter.ProfitsPresenter;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.member.provider.IMemberProvider;
import com.sanpu.kxe.business.trade.provider.ITradeProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.view.NoScrollViewPager;
import com.sanpu.kxe.common.view.ScrollableFragment;
import com.sanpu.kxe.jump.eventbus.RefreshPersonEvent;
import com.sanpu.kxe.jump.eventbus.RefreshProfitsEvent;
import com.sanpu.kxe.module.immersionbar.ImmersionBar;
import com.sanpu.kxe.module.roundview.RoundTextView;
import com.sanpu.kxe.module.scrollable.CanScrollVerticallyDelegate;
import com.sanpu.kxe.module.scrollable.OnFlingOverListener;
import com.sanpu.kxe.module.scrollable.ScrollableLayout;
import com.sanpu.kxe.module.widget.NumberRunningTextView;
import com.sanpu.kxe.module.widget.VerticalSwipeRefreshLayout;
import com.sanpu.kxe.module.widget.WaveHelper;
import com.sanpu.kxe.module.widget.WaveView;
import com.sanpu.kxe.rxservice.RequestMap;
import com.sanpu.kxe.utils.PublicProviderUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Description：收益
 * Created by 薛勇军 on 2018/7/9.
 */

public class ProfitsFragment extends BaseFragment implements ProfitsContract.View {

    @Bind(R.id.wave)
    WaveView vWave;
    @Bind(R.id.day_amount)
    TextView vDayAmount;
    @Bind(R.id.withdraw_amount)
    NumberRunningTextView vWithdrawAmount;
    @Bind(R.id.amount)
    TextView vAmount;
    @Bind(R.id.back)
    ImageView vBack;
    @Bind(R.id.team_title)
    TextView vTeamTitle;
    @Bind(R.id.person_count)
    TextView vPersonCount;
    @Bind(R.id.navigation)
    LinearLayout vNavigation;
    @Bind(R.id.indicator_layout)
    LinearLayout vIndicatorLayout;

    @Bind(R.id.view_pager)
    NoScrollViewPager vViewPager;
    @Bind(R.id.scrollable_layout)
    ScrollableLayout vScrollableLayout;
    @Bind(R.id.swipeRefreshLayout)
    VerticalSwipeRefreshLayout vSwipeRefreshLayout;

    private ProfitsPagerAdapter mPagerAdapter;

    private ProfitsContract.Presenter mPresenter;

    private String withdrawMoney = "0";

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_profits;
    }

    @Override
    protected void initView() {
        super.initView();
        WaveHelper waveHelper = new WaveHelper(vWave);
        vWave.setShapeType(WaveView.ShapeType.SQUARE);
        waveHelper.start();

        vTeamTitle.setText("一级盟友列表");
        mPagerAdapter = new ProfitsPagerAdapter(getActivity().getSupportFragmentManager());
        vScrollableLayout.setDraggableView(vNavigation);
        vScrollableLayout.setCanScrollVerticallyDelegate(new CanScrollVerticallyDelegate() {
            @Override
            public boolean canScrollVertically(int direction) {
                final ScrollableFragment fragment = mPagerAdapter.getItem(vViewPager.getCurrentItem());
                return fragment != null && fragment.canScrollVertically(direction);
            }
        });

        vViewPager.setNoScroll(true);
        vViewPager.setOffscreenPageLimit(3);
        vViewPager.setAdapter(mPagerAdapter);
        vScrollableLayout.setOnFlingOverListener(new OnFlingOverListener() {
            @Override
            public void onFlingOver(int y, long duration) {
                final ScrollableFragment fragment = mPagerAdapter.getItem(vViewPager.getCurrentItem());
                if (fragment != null) {
                    fragment.onFlingOver(y, duration);
                }
            }
        });
        vViewPager.setCurrentItem(0);
        mPresenter = new ProfitsPresenter(this);
        mPresenter.indicatorView();
        mPresenter.getRebateTotal();
    }

    @Override
    protected void setListener() {
        super.setListener();
        vSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getRebateTotal();
                mPagerAdapter.getItem(vViewPager.getCurrentItem()).setOnRefresh();
            }
        });
        vViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mPresenter.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        vBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    vViewPager.setCurrentItem(vViewPager.getCurrentItem() - 1);
                    if (vViewPager.getCurrentItem() > 0) {
                        String merchantName = mPagerAdapter
                                .getItem(vViewPager.getCurrentItem() - 1).getMerchantName();
                        vTeamTitle.setText(TextUtils.isEmpty(merchantName) ? "一级盟友列表" : merchantName + "盟友列表");
                    } else {
                        vTeamTitle.setText("一级盟友列表");
                    }
                    int personCount = mPagerAdapter.getItem(vViewPager.getCurrentItem()).getPersonCount();
                    vPersonCount.setText("(" + personCount + ")");
                    switch (vViewPager.getCurrentItem()) {
                        case 0:
                            vBack.setBackgroundResource(R.drawable.ic_promotion_left_point1);
                            break;
                        case 1:
                            vBack.setBackgroundResource(R.drawable.ic_promotion_back);
                            break;
                        case 2:
                            vBack.setBackgroundResource(R.drawable.ic_promotion_back);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.leftLl, R.id.rightLl, R.id.toplist_layout, R.id.upgrade_layout, R.id.day_amount_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftLl:
                ITradeProvider provider = PublicProviderUtil.getProvider(ITradeProvider.class);
                if (provider != null) {
                    provider.openWithdrawActivity(getContext(), null);
                }
                break;
            case R.id.rightLl:
                String url = UrlConstants.ALLYCOUNT + "?" + new RequestMap().map2ReqStr();
                MainOpenProvider.getInstance().openBrowserX5Activity(getContext(), url, true);
                break;
            case R.id.toplist_layout:
                String shareUrl = UrlConstants.SHAREAPP + "?" + new RequestMap().map2ReqStr();
                MainOpenProvider.getInstance().openBrowserX5Activity(getContext(), shareUrl, true);
                break;
            case R.id.upgrade_layout:
                IMemberProvider memberProvider = PublicProviderUtil.getProvider(IMemberProvider.class);
                if (memberProvider != null) {
                    memberProvider.openMemberLevelsListActivity(getContext());
                }
                break;
            case R.id.day_amount_layout:
                ITradeProvider tradeProvider = PublicProviderUtil.getProvider(ITradeProvider.class);
                if (tradeProvider != null) {
                    tradeProvider.openMyRebTotalActivity(getContext(), 0);
                }
                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisible()) {
            ImmersionBar mImmersionBar = ImmersionBar.with(this);
            mImmersionBar.statusBarColorTransformEnable(true)
                    .statusBarView(ButterKnife.findById(mRootView, R.id.topView))
                    .navigationBarWithKitkatEnable(false)
                    .init();

            if (vWithdrawAmount != null) {
                vWithdrawAmount.setContent(withdrawMoney);
            }
        }
    }

    @Override
    public void addIndicatorView(RoundTextView indicator) {
        if (indicator != null) {
            vIndicatorLayout.addView(indicator);
        }
    }

    @Override
    public void showRebateTotalView(RebateTotalOutput output) {
        if (output == null) {
            output = CacheManage.getInstance().getCache(CacheModel.REBATETOTAL);
        }
        if (output != null) {
            if (output.getWithdrawAmt() != null) {
                withdrawMoney = output.getWithdrawAmt().toPlainString();
            }
            vWithdrawAmount.setContent(withdrawMoney);
            if (output.getDayRebAmt() != null) {
                vDayAmount.setText(output.getDayRebAmt().toPlainString());
            }
            if (output.getAccRebAmt() != null) {
                vAmount.setText(output.getAccRebAmt().toPlainString());
            }
        }
        if (vSwipeRefreshLayout.isRefreshing()) {
            vSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshPerson(RefreshPersonEvent event) {
        if (event != null) {
            vPersonCount.setText("(" + event.getCount() + ")");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshProfits(RefreshProfitsEvent event) {
        if (event != null) {
            if (event.getId() > 1) return;
            int id = event.getId() + 1;
            vViewPager.setCurrentItem(id);
            mPagerAdapter.getItem(id).loadData(event.getMerchantCode(), event.getAccountName());
            if (!TextUtils.isEmpty(event.getMerchantName())) {
                vTeamTitle.setText(""+event.getMerchantName() + "盟友列表");
            } else {
                vTeamTitle.setText(""+event.getAccountName() + "盟友列表");
            }
            switch (id) {
                case 0:
                    vBack.setBackgroundResource(R.drawable.ic_promotion_left_point1);
                    break;
                case 1:
                    vBack.setBackgroundResource(R.drawable.ic_promotion_back);
                    break;
                case 2:
                    vBack.setBackgroundResource(R.drawable.ic_promotion_back);
                    break;
            }
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(ProfitsContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
